import { Leafer, Pen, DragEvent, App, Rect, Ellipse, Polygon } from 'leafer-ui'
import { ITool, IToolConfig } from '../types'
export const ShapeTool: ITool = ({ app, config, commit, target }) => {
	let shape: Rect | Ellipse | Polygon | null = null
	let isDrawing = false
	let startPoint = { x: 0, y: 0 }
	const startDrawing = (e: DragEvent) => {
		if (e?.multiTouch) return (isDrawing = false)
		if (app.editor.editing) return
		isDrawing = true
		const point = e.getPagePoint()
		startPoint = { x: point.x, y: point.y }
		const attrs = {
			width: 0,
			height: 0,
			fill: 'transparent',
			x: point.x,
			y: point.y,
			stroke: config.shape.color,
			strokeWidth: config.shape.strokeWidth / (app.data?.fitScale ?? 1),
			// editable: true
		}
		switch (config.shape.type) {
			case 'rect':
				shape = new Rect(attrs)
				break
			case 'square':
				shape = new Rect(attrs)
				break
			case 'circle':
				shape = new Ellipse(attrs)
				break
			case 'triangle':
				shape = new Polygon({
					...attrs,
					sides: 3
				})
				break
		}
		target().add(shape)
	}
	const continueDrawing = (e: DragEvent) => {
		if (e?.multiTouch) return (isDrawing = false)
		if (!isDrawing || !shape) return
		const point = e.getPagePoint()
		// 根据拖拽距离计算宽度和高度
		const width = Math.abs(point.x - startPoint.x)
		const height = Math.abs(point.y - startPoint.y)
		// 更新矩形尺寸
    //如果按住shift键,或者配置为正方形，则宽高一致
		if (e.shiftKey||(config.shape.type === 'square')) {
			shape.width = shape.height = Math.max(width, height)
		} else {
			shape.width = width
			shape.height = height
		}

		// 如果从右下向左上拖拽，更新位置
		shape.x = Math.min(startPoint.x, point.x)
		shape.y = Math.min(startPoint.y, point.y)
	}
	const stopDrawing = () => {
		isDrawing = false
		shape = null // 重置形状引用，准备下一次绘制
		commit();
	}
	const eventsMap = {
		[DragEvent.START]: startDrawing,
		[DragEvent.DRAG]: continueDrawing,
		[DragEvent.END]: stopDrawing
	}
	return {
		eventsMap,
		active: () => {},
		deactive: () => {}
	}
}
